package com.itcodai.config.exception;

import com.itcodai.entity.JsonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * @author c-fanqj
 * @date 2023/3/31
 * @apiNote 全局异常处理类
 */
// basePackages 属性，该属性是用来拦截哪个包中的异常信息，
// 一般我们不指定这个属性，我们拦截项目工程中的所有异常
@ControllerAdvice
@ResponseBody
//@RestControllerAdvice
public class GlobalExceptionHandler {

    // 打印日志
    private final Logger logger =
            LoggerFactory.getLogger(this.getClass());

    /**
     * 拦截业务异常，返回业务异常信息
     * @param ex
     * @return
     */
    @ExceptionHandler(BusinessErrorException.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public JsonResult handleBusinessError(BusinessErrorException ex) {
        logger.error("业务异常信息：", ex);
        String code = ex.getCode();
        String message = ex.getMessage();
        return new JsonResult(code, message);
    }

    /**
     * 空指针异常处理
     * @param ex NullPointerException
     * @return
     */
    @ExceptionHandler(NullPointerException.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public JsonResult handleTypeMismatchException(NullPointerException ex) {
        logger.error("空指针异常，{}", ex);
        //return new JsonResult("500", "空指针异常了");
        return new JsonResult("500", "空指针异常了", ex.getMessage());
    }

    /**
     * 缺少请求参数异常处理
     * @param ex HttpMessageNotReadableException
     * @return
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public JsonResult handleHttpMessageNotReadableException(
            MissingServletRequestParameterException ex) {
        logger.error("缺少请求参数，{}", ex);
        //return new JsonResult("400", "缺少必要的请求参数");
        return new JsonResult("400", "缺少必要的请求参数", ex.getMessage());
    }

    /**
     * 系统异常 预期以外异常
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public JsonResult handleUnexpectedServer(Exception ex) {
        logger.error("系统异常：", ex);
        //return new JsonResult("500", "系统发生异常，请联系管理员");
        return new JsonResult("500", "系统发生异常，请联系管理员", ex.getMessage());
    }

}
